﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IProductReviewRepository))]
    public partial class EntityRepositories : IProductReviewRepository
    {
        #region ProductReview

        public IQueryable<IProductReview> ProductReviews
        {
            get
            {
                return this.DataReaderContext.ProductReviews;
            }
        }

        public void Post(IProductReview productReview)
        {
            Contract.Requires(productReview != null);

            var item = new ProductReview()
            {
                CreateDate = productReview.CreateDate,
                IsPublished = productReview.IsPublished,
                OrderId = productReview.Order.Id,
                ProductId = productReview.Product.Id,
                Rate = (int)productReview.Rate,
                Remark = productReview.Remark,
                CustomerId = productReview.Customer.Id
            };

            this.DataWriterContext.ProductReviews.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(IProductReview productReview)
        {
            Contract.Requires(productReview != null);

            var item = this.DataWriterContext.ProductReviews
                .Where(i => i.Id == productReview.Id)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("ProductReview: " + productReview.Id);

            }

            item.CreateDate = productReview.CreateDate;
            item.IsPublished = productReview.IsPublished;
            item.OrderId = productReview.Order.Id;
            item.ProductId = productReview.Product.Id;
            item.Rate = (int)productReview.Rate;
            item.Remark = productReview.Remark;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(IProductReview productReview)
        {
            if (productReview != null)
            {
                var item = this.DataWriterContext.ProductReviews
                .Where(i => i.Id == productReview.Id)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.ProductReviews.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

        #endregion
    }
}
